package com.example.bigevent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bigevent.pojo.Article;
import com.example.bigevent.mapper.ArticleMapper;
import com.example.bigevent.pojo.PageBean;
import com.example.bigevent.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bigevent.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-30
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {
    /**
     * 新增文章
     * @param article
     * @return
     */
    @Override
    public void addArticle(Article article) {
        //根据线程获取id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId)
                .setCreateTime(LocalDateTime.now())
                .setUpdateTime(LocalDateTime.now());
        save(article);
    }
    /**
     * 文章列表(条件分页)
     * @param pageNum
     * @param pageSize
     * @param categoryId
     * @param state
     * @return
     */
    @Override
    public PageBean<Article> listArticle(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建Page类对象
        Page<Article> page = new Page<>(pageNum, pageSize);
        // 查询结果返回到page中的records属性中
        page(page, new LambdaQueryWrapper<Article>().eq(categoryId != null,Article::getCategoryId, categoryId)
                .eq(state != null,Article::getState, state));
        return new PageBean<>(page.getTotal(),page.getRecords());
    }
    /**
     * 更新文章
     * @param article
     * @return
     */
    @Override
    public void updateArticle(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        updateById(article);
    }
}
